package com.zl.zlproject.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DrawFilter;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;


/**
 * Created by 郑磊 on 2018/6/8.
 */

public class WaveeView extends View {

    private Path mAbovePath,mBelowWavePath;
    private Paint mAboveWavePaint,mBelowWavePaint;
    private DrawFilter mDrawFilter;
    private  float f;
    private  OnWaveAnimationListener mOnWaveAnimationListener;
    private int mColor;

    public WaveeView(Context context) {
        this(context,null);
    }

    public WaveeView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);


        //初始化路径
        mAbovePath =new Path();
        mBelowWavePath =new Path();


        //初始化画笔
        mAboveWavePaint =new Paint(Paint.ANTI_ALIAS_FLAG);
        mAboveWavePaint.setAntiAlias(true);
        mAboveWavePaint.setStyle(Paint.Style.FILL);

        mBelowWavePaint =new Paint(Paint.ANTI_ALIAS_FLAG);
        mBelowWavePaint.setAntiAlias(true);
        mBelowWavePaint.setStyle(Paint.Style.FILL);

        mBelowWavePaint.setColor( Color.WHITE);
        mAboveWavePaint.setColor( Color.WHITE);

        mBelowWavePaint.setAlpha(80);

        //画布抗锯齿
        mDrawFilter = new PaintFlagsDrawFilter(0,Paint.ANTI_ALIAS_FLAG| Paint.FILTER_BITMAP_FLAG);



    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.setDrawFilter(mDrawFilter);

        mAbovePath.reset();
        mBelowWavePath.reset();

        f -= 0.1f;
        float y1,y2;
        double d = 2*Math.PI/getWidth();

        mAbovePath.moveTo(getLeft(),getBottom());
        mBelowWavePath.moveTo(getLeft(),getBottom());

        for (float x=0; x<=getWidth();x+=20){
            y1 =(float)(8*Math.cos(d*x+f)+16);
            y2 = (float)(8*Math.sin(d*x+f));
            mAbovePath.lineTo(x,y1);
            mBelowWavePath.lineTo(x,y2);
            //回调 把y1的值传出去 让外部的图片随波浪滚动
            if(mOnWaveAnimationListener!=null) {
                mOnWaveAnimationListener.onWaveAnimation(y1);
            }
        }

        mAbovePath.lineTo(getRight(),getBottom());
        mBelowWavePath.lineTo(getRight(),getBottom());

        canvas.drawPath(mAbovePath,mAboveWavePaint);
        canvas.drawPath(mBelowWavePath,mBelowWavePaint);
        postInvalidateDelayed(20);
    }

    public interface OnWaveAnimationListener{
        void onWaveAnimation(float y);
    }

    public void setOnWaveAnimationListener(OnWaveAnimationListener onWaveAnimationListener){
        this.mOnWaveAnimationListener =onWaveAnimationListener;
    }






}
